package com.ruoyi.web.controller.system.factory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.SysCode;
import com.ruoyi.system.service.SysCodeService;
import com.ruoyi.web.core.JoController;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Log4j2
@Component
public class SysCodeFactory extends JoController
{
    @Autowired
    private SysCodeService sysCodeService;

    /**
     * 创建编码
     *
     * @param i 创建个数
     */
    public List<SysCode> build(Integer i)
    {
        List<SysCode> list = new ArrayList<>();
        for (int j = 0; j < i; j++)
        {
            list.add(SysCode.builder().code(IdUtils.simpleUUID()).build());
        }
        log.info("[{}]:{})({}", "generate system code", getUserId(), i);
        delAll();
        sysCodeService.saveBatch(list);
        return list;
    }

    /**
     * 删除所有
     */
    private boolean delAll()
    {
        return sysCodeService.remove(new LambdaQueryWrapper<SysCode>().eq(SysCode::getDelFlag, 0));
    }

    /**
     * @param code 编码
     * @return 执行结果
     */
    public boolean check(String code)
    {
        return sysCodeService.update(new LambdaUpdateWrapper<SysCode>()
                .eq(SysCode::getCode, code)
                .eq(SysCode::getDelFlag, 0)
                .set(SysCode::getUpdateTime, LocalDateTime.now())
                .set(SysCode::getCode, code + ">>" + IpUtils.getIpAddr())
                .set(SysCode::getDelFlag, "1")
        );
    }
}
